#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This code creates new orders from a text file"""

__author__ = 'felipel+bulk@google.com (Felipe Lora)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
import time
sys.path.insert(0, os.path.join('..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle.common import Utils
from adspygoogle.dfp.DfpClient import DfpClient
from adspygoogle.dfp import DfpUtils
from adspygoogle.dfp.DfpErrors import *

# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))

# Initialize appropriate service. By default, the request is always made against
# the production environment.
order_service = client.GetOrderService('https://www.google.com', 'v201111')
company_service = client.GetCompanyService('https://www.google.com', 'v201111')
user_service = client.GetUserService('https://www.google.com', 'v201111')

# Get orders by statement.
networkOrders = DfpUtils.GetAllEntitiesByStatementWithService(order_service)
networkCompanies = DfpUtils.GetAllEntitiesByStatementWithService(company_service)
networkUsers = DfpUtils.GetAllEntitiesByStatementWithService(user_service)

# Define names of logs
warningLog = "warnings_orders.log"
errorLog = "errors_orders.log"
successLog = "success_orders.log"

def getFileOrders(oFile):

  orders = []
  oFile = open(oFile,'rU')
  orderValidator = 1

  for line in oFile.readlines():
    campaign = { }  
    currLine = line.rsplit("^")
    
    campaign['name'] = currLine[0]
    campaign['advertiserId'] = currLine[1]
    if len(currLine[2].rsplit("\n")) > 0:
      campaign['traffickerId'] = currLine[2].rsplit("\n")[0]
    else:
      campaign['traffickerId'] = currLine[2]
    if len(currLine[3].rsplit("\n")) > 0:
      campaign['externalOrderId'] = currLine[3].rsplit("\n")[0]
    else:
      campaign['externalOrderId'] = currLine[3]
    if len(currLine) < 5:
      campaign['poNumber'] = ''
    else:  
      campaign['poNumber'] = currLine[4].rsplit("\n")[0]
    
    order_indexer = dict((n['name'], i) for i,n in enumerate(networkOrders))
    advertiser_indexer = dict((n['name'], i) for i,n in enumerate(networkCompanies))
    trafficker_indexer = dict((n['email'], i) for i,n in enumerate(networkUsers))
    orderValidator = validateOrder(campaign,order_indexer,advertiser_indexer,trafficker_indexer)
    
    if orderValidator == 1:
       orders.append(campaign)

  return orders

def validateOrder(campaign,order_indexer,advertiser_indexer,trafficker_indexer):
  f = open(errorLog,'a')
  flag = 1
  m = ""
  
  if campaign['name'] in order_indexer:
    flag = 0
    m = "%s, an order with the same name already exists in your network\n" % campaign['name']
  
  if campaign['advertiserId'] not in advertiser_indexer:
    flag = 0
    m = m + "%s, the advertiser %s for this order does not exist\n" % (campaign['name'],campaign['advertiserId'])
  
  if campaign['traffickerId'] not in trafficker_indexer:
    flag = 0
    m = m + "%s, the trafficker %s for this order does not exist\n" % (campaign['name'],campaign['traffickerId'])
  
  if len(campaign['poNumber']) > 63:
    flag = 0
    m = m + "%s, the PO number %s for this order exceeds the 63 character limit\n" % (campaign['name'],campaign['poNumber'])

  f.write(m)
  f.close()

  return flag
  
def createOrders(orders):
  advertiser_indexer = dict((n['name'], i) for i,n in enumerate(networkCompanies))
  trafficker_indexer = dict((n['email'], i) for i,n in enumerate(networkUsers))
  
  for order in orders:
    order['advertiserId'] = networkCompanies[advertiser_indexer[order['advertiserId']]]['id']
    order['traffickerId'] = networkUsers[trafficker_indexer[order['traffickerId']]]['id']
  
  # Create the orders
  try: 
    orders_created = order_service.CreateOrders(orders)
    fs = open(successLog,'a')
    for oCreated in orders_created:
      m = "%s,%s\n" % (oCreated['id'],oCreated['name'])
      fs.write(m)      
    fs.close()

  except DfpRequestError,e:
    if "UniqueError.NOT_UNIQUE" in e.fault_string:
      warningLogFile = open(warningLog,'a')
      message = "Ouch - DUPLICATE ORDER - This message should not have appeared!\n" 
      warningLogFile.write(message)
      warningLogFile.close()
    else:
      warningLogFile = open(warningLog,'a')
      message = "%s\n"  % (e.fault_string)
      warningLogFile.write(message)
      warningLogFile.close()
  
def Main():
  # Clean old logs
  f = open(warningLog,'w')
  f.write("Name, Message\n")
  f.close()
  f = open(errorLog,'w')
  f.write("Name, Message\n")
  f.close()
  f = open(successLog,'w')
  f.write("ID, Name\n")
  f.close()

  # Read the ad units from the text file
  args = sys.argv[1:]
  oFile = args[0]
  orders = getFileOrders(oFile)
  # Create the orders
  print "Creation begins here for the orders"
  createOrders(orders)
  
if __name__ == '__main__':
  Main()
